import * as ysApi from "@/apis/g.ys";
import { getCachedValue } from "@/utils/local-storage-cache";
import { Subject, distinctUntilChanged, filter } from "rxjs";
import { computed, defineComponent, onMounted, onUnmounted, ref, watch } from "vue";
import styles from "./Characters.module.scss";
import { useYsStore } from "./store";

import { VIEW_PADDING_TOP } from "@/constants";

type ExtValueUrl = { name: string; url: string };
type ExtValue = string | ExtValueUrl[];
type Ext = { [code: string]: ExtValue };

type YsCharacter = {
  name: string;
  infoId: number;
  avatarUrl: string;
  lihuiUrl: string;
  namePicUrl: string;
  elementIconUrl: string;
  descHtml: string;
  quotePicUrl: string;
};
/**
 * 732_0  头像
 * 732_1  pc立绘
 * 732_15 移动端立绘
 * 732_2  名字图
 * 732_3  元素图标
 * 732_7  一段 html 介绍
 * 732_8  图片语录
 */

function itemToCharacter(it: DYsContentItem): YsCharacter {
  const ext: Ext = JSON.parse(it.sExt);
  return {
    name: it.sTitle,
    infoId: it.iInfoId,
    avatarUrl: (ext["732_0"] as ExtValueUrl[])[0].url,
    lihuiUrl: (ext["732_1"] as ExtValueUrl[])[0].url,
    namePicUrl: (ext["732_2"] as ExtValueUrl[])[0].url,
    elementIconUrl: (ext["732_3"] as ExtValueUrl[])[0].url,
    descHtml: ext["732_7"] as string,
    quotePicUrl: (ext["732_8"] as ExtValueUrl[])[0].url,
  };
}

const Characters = defineComponent({
  setup() {
    const ysStore = useYsStore();
    const cid = computed(() => ysStore.activeNation?.chanId);
    const characters = ref<YsCharacter[]>([]);

    const loadCharacters = async (chanId: string) => {
      try {
        const cacheKey = `__ys_nation_${chanId}_characters__`;
        const pager = await getCachedValue(cacheKey, 3600 * 24 * 7, () => ysApi.getByChanId({ chanId }));
        console.log("pager", pager);
        characters.value = pager.list.map(itemToCharacter);
      } catch (err) {
        console.error(`Error occurs when getting ys characters in nation ${chanId}:`, err);
      }
    };

    const cidSubject = new Subject<string>();
    const cidSubscription = cidSubject
      .pipe(filter((it) => !!it))
      .pipe(distinctUntilChanged())
      .subscribe((chanId) => {
        console.log("load on change ", chanId);
        loadCharacters(chanId);
      });

    watch(cid, (newCid) => {
      cidSubject.next(newCid);
    });

    onMounted(() => {
      cidSubject.next(cid.value);
    });

    onUnmounted(() => {
      cidSubscription.unsubscribe();
    });

    return () => (
      <div style={{ paddingTop: VIEW_PADDING_TOP }} class={styles.characters}>
        <div style={{ border: "1px solid red", flex: "1" }}>
          顶顶顶
          {cid.value}
          <pre style={{ height: "400px", width: "1000px", overflow: "auto" }}>
            {JSON.stringify(characters.value, null, 2)}
          </pre>
        </div>
      </div>
    );
  },
});

export default Characters;
